package com.kele.system.service.impl;

import com.kele.system.mapper.RoleMapper;
import com.kele.system.model.dto.RoleDto;
import com.kele.system.model.entity.Role;
import com.kele.system.model.entity.UserRole;
import com.kele.system.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Author: Kele
 * @CreateDate: 2023/4/26 14:50
 * @Version:
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public List<RoleDto> getRoleByUserid(String userId) {
        List<Role> roleByUserId = roleMapper.getRoleByUserId(userId);
        List<RoleDto> allRole = roleMapper.getAllRole();

        Map<String, RoleDto> map = allRole.stream().collect(Collectors.toMap(RoleDto::getId, Function.identity(), (key1, key2) -> key2));

        for (Role role : roleByUserId) {
            RoleDto roleDto = map.get(role.getId());
            if (roleDto != null){
                roleDto.setSelect(true);
                map.put(role.getId(), roleDto);
            }
        }
        return new ArrayList<>(map.values());
    }

    @Override
    public void assignRole(String userId, List<String> roleIds, String creatorId) {
        // 删除用户的所有角色信息
        roleMapper.deleteUserRole(userId);
        // 添加角色信息
        List<UserRole> userRoles = new ArrayList<>(roleIds.size());

        for (String roleId : roleIds) {
            UserRole userRole = new UserRole();
            userRole.setId(UUID.randomUUID().toString().replace("-", ""));
            userRole.setUserId(userId);
            userRole.setRoleId(roleId);
            userRole.setCreateTime(LocalDateTime.now());
            userRole.setCreator(creatorId);

            userRoles.add(userRole);
        }

        // 入库
        roleMapper.batchInsert(userRoles);
    }
}
